package com.dom4j;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.dl.DL;

//读写消费记录.xml信息
public class XF extends SJH{
	static Document document = null;
	public static Element root = null;
	static {
		SAXReader reader = new SAXReader();
		try {
			document = reader.read("消费记录.xml");
			root = document.getRootElement();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}//删除手机号
	public  static void sc(String str){
		Iterator it =root.elementIterator();
		while(it.hasNext()){
			Element element=(Element)it.next();
			if(element.attributeValue("num").equals(str)){
				element.getParent().remove(element);
			}
		}
		sava();
	}
	//显示消费的时间
	public static String date() {
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
		return format.format(date);
	}
//保存信息
	private static void sava() {
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = null;
		try {
			writer = new XMLWriter(new FileWriter("消费记录.xml"), format);
			writer.write(document);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	//添加信息
public static void add(String str){
	Element element = root.addElement("手机号");
	element.addAttribute("num", str);
	Element cElement1 = element.addElement("通话");
	cElement1.addAttribute("id", "1");
	Element cElement2 = element.addElement("上网");
	cElement2.addAttribute("id", "1");
	Element cElement3 = element.addElement("短信");
	cElement3.addAttribute("id", "1");
	sava();
}
//消费的具体时间和内容，写入到XML里面。
	public static void XF(String date1, String date2, String lx) {
		Iterator it = root.elementIterator();
		while (it.hasNext()) {
			Element element = (Element) it.next();
			if (DL.num.equals(element.attributeValue("num"))) {
				List<Element> list = element.elements(lx);
				Element cElement = list.get(list.size()-1);
				Integer num = list.size()+1;
				String str = date1 + "开始" + lx + "，" + date2 + "结束";
				if (!cElement.getText().equals("")) {
					Element cElement1 = element.addElement(lx);
					cElement1.addAttribute("id", num.toString());
					cElement1.setText(str);
				} else {
					cElement.setText(str);
				}
				sava();
			}
		}
	}
}
